import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Game2048 extends JPanel {
    private static final int SIZE = 4;

    private  final int[][] grid = new int[SIZE][SIZE];

    private final Random random = new Random();

    Game2048(){
        spawnTile();
        spawnTile();
    }

    private void spawnTile(){
        int x,y;
        do{
            x = random.nextInt(SIZE);
            y = random.nextInt(SIZE);
        }while(grid[x][y]!=0);
        grid[x][y] = random.nextInt(10)<5 ? 2:4;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.lightGray);
        g.fillRect(0,0,getWidth(),getHeight());
        for(int i = 0; i<SIZE; i++){
            for(int j = 0; j<SIZE; j++){
                //画小格子
                drawTile(g,grid[i][j],i*100,j*100);
            }
        }
    }
    private void drawTile(Graphics g, int value, int x, int y){
        int r = (int)(Math.log(value)/Math.log(2));
        g.setColor(value == 0 ?Color.GRAY : new Color(255-r*20,240,200));
        g.fillRect(x,y,100,100);
        g.setColor(Color.BLACK);
        g.drawRect(x,y,100,100);

        if(value != 0){
            String text = String.valueOf(value);
            FontMetrics fm = g.getFontMetrics();
            int w = fm.stringWidth(text);
            int h = fm.getHeight();
            int a = fm.getAscent();
            int textX = x + (100-w)/2;
            int textY = y + (100-h)/2 + a;
            g.drawString(text,textX,textY);
        }
    }



    public static void main(String[] args) {
        JFrame frame = new JFrame("2048 Game");
        frame.setSize(420,460);
        Game2048 game2048 = new Game2048();
        frame.add(game2048);
        frame.setVisible(true);
    }
}